<template>
  <view class="pick-bottle-container planet-bg">
    <!-- 星空背景 -->
    <view class="stars">
      <view v-for="star in stars" :key="star.id" class="star" :style="star.style"></view>
    </view>
    
    <!-- 页面标题 -->
    <view class="header">
      <text class="title">捞取漂流瓶</text>
      <text class="subtitle">在宇宙的海洋中寻找神秘的漂流瓶</text>
    </view>
    
    <!-- 主要内容区 -->
    <view class="main-content">
      <!-- 海洋动画 -->
      <view class="ocean">
        <!-- 漂流瓶动画 -->
        <view class="bottle-animation">
            <view class="bottle" :class="{ 'floating': !isPicking, 'caught': isPicking }" :style="{ transform: `translateY(${bottleTransform.y}rpx) rotate(${bottleTransform.rotate}deg)` }">
            <view class="bottle-neck"></view>
            <view class="bottle-body">
              <text class="bottle-text">{{ currentBottle ? currentBottle.content.substring(0, 20) + '...' : '🎣 点击捞取' }}</text>
            </view>
            <view class="bottle-cap"></view>
          </view>
        </view>
      </view>
      
      <!-- 捞取按钮 -->
      <button 
        class="btn btn-primary pick-btn"
        @tap="pickBottle"
        :disabled="isPicking"
      >
        {{ isPicking ? '捞取中...' : '🎣 捞取漂流瓶' }}
      </button>
      
      <!-- 漂流瓶信息卡片 -->
      <view class="bottle-card" v-if="currentBottle && showBottleDetail">
        <view class="bottle-info">
          <text class="from-text">来自: {{ currentBottle.from || '未知星球' }}</text>
          <text class="time-text">{{ formatRelativeTime(currentBottle.time) }}</text>
        </view>
        <view class="bottle-content">
          {{ currentBottle.content }}
        </view>
        <view class="bottle-actions">
          <button class="btn btn-outline respond-btn" @tap="respondToBottle">回复</button>
          <button class="btn btn-outline like-btn" @tap="likeBottle">喜欢</button>
          <button class="btn btn-outline collect-btn" @tap="collectBottle">收藏</button>
        </view>
      </view>
      
      <!-- 捞取统计 -->
      <view class="stats">
        <text class="stat-item">今日已捞: {{ todayPicked }}个</text>
        <text class="stat-item">总捞取: {{ totalPicked }}个</text>
      </view>
    </view>
    
    <!-- 底部提示 -->
    <view class="footer">
      <text class="tip-text">💡 每天最多可捞取5个漂流瓶</text>
    </view>
  </view>
</template>

<script>
  import { pickBottle as pickBottleApi } from '../../src/api/bottle/bottleApi';
  import { showToast, formatRelativeTime } from '../../src/common/tools';
  
  export default {
    data() {
      return {
        currentBottle: null,
        showBottleDetail: false,
        isPicking: false,
        todayPicked: 0,
        totalPicked: 0,
        stars: [],
        bottleTransform: { // 用于控制漂流瓶动画的样式数据
          y: 0,
          rotate: 0
        },
        // 模拟漂流瓶数据池
        mockBottles: [
          {
            id: 'mock-1',
            content: '在遥远的星系中，是否有另一个我在仰望着同一片星空？',
            from: '仙女座星系',
            time: new Date(Date.now() - Math.random() * 86400000 * 7).toISOString()
          },
          {
            id: 'mock-2',
            content: '宇宙如此浩瀚，我们的相遇是多么奇妙的缘分！',
            from: '银河系',
            time: new Date(Date.now() - Math.random() * 86400000 * 7).toISOString()
          },
          {
            id: 'mock-3',
            content: '希望这个漂流瓶能带给你好运和快乐！',
            from: '地球',
            time: new Date(Date.now() - Math.random() * 86400000 * 7).toISOString()
          },
          {
            id: 'mock-4',
            content: '每一颗星星都有属于自己的故事，你愿意听听我的吗？',
            from: '火星',
            time: new Date(Date.now() - Math.random() * 86400000 * 7).toISOString()
          },
          {
            id: 'mock-5',
            content: '当你看到这个漂流瓶时，我可能已经在另一个时空了...',
            from: '未来',
            time: new Date(Date.now() - Math.random() * 86400000 * 7).toISOString()
          }
        ]
      };
    },
    onLoad() {
      // 初始化星空背景
      this.initStars();
      // 加载捞取统计
      this.loadStats();
    },
    methods: {
      // 时间格式化方法
      formatRelativeTime,
      
      // 初始化星空背景
      initStars() {
        const starCount = 150;
        const tempStars = [];
        
        for (let i = 0; i < starCount; i++) {
          // 随机位置
          const x = Math.random() * 100;
          const y = Math.random() * 100;
          
          // 随机动画时长
          const duration = 2 + Math.random() * 3;
          
          // 随机大小
          const size = 1 + Math.random() * 3;
          
          // 随机透明度
          const opacity = 0.3 + Math.random() * 0.7;
          
          tempStars.push({
            id: `star-${i}`,
            style: {
              left: `${x}%`,
              top: `${y}%`,
              width: `${size}rpx`,
              height: `${size}rpx`,
              opacity: opacity,
              '--duration': `${duration}s`
            }
          });
        }
        
        this.stars = tempStars;
      },
      
      // 加载捞取统计
      loadStats() {
        // 从本地存储获取统计数据
        const today = new Date().toDateString();
        const lastPickDate = uni.getStorageSync('lastPickDate');
        const savedTodayPicked = uni.getStorageSync('todayPicked');
        const savedTotalPicked = uni.getStorageSync('totalPicked');
        
        // 如果日期不同，重置今日捞取数
        if (lastPickDate !== today) {
          this.todayPicked = 0;
          uni.setStorageSync('todayPicked', 0);
          uni.setStorageSync('lastPickDate', today);
        } else {
          this.todayPicked = savedTodayPicked || 0;
        }
        
        this.totalPicked = savedTotalPicked || 0;
      },
      
      // 捞取漂流瓶
      async pickBottle() {
        // 检查今日捞取数量是否已达上限
        if (this.todayPicked >= 5) {
          showToast('今日捞取已达上限，请明天再来');
          return;
        }
        
        try {
          this.isPicking = true;
          this.showBottleDetail = false;
          
          // 添加捞取动画效果
          this.bottleTransform = { y: -50, rotate: 10 };
          
          // 模拟网络延迟
          await new Promise(resolve => setTimeout(resolve, 1500));
          
          // 从模拟数据池中随机选择一个漂流瓶
          const randomIndex = Math.floor(Math.random() * this.mockBottles.length);
          this.currentBottle = { ...this.mockBottles[randomIndex] };
          
          // 显示漂流瓶详情
          this.showBottleDetail = true;
          
          // 更新统计数据
          this.todayPicked++;
          this.totalPicked++;
          
          // 保存到本地存储
          uni.setStorageSync('todayPicked', this.todayPicked);
          uni.setStorageSync('totalPicked', this.totalPicked);
          
          // 播放成功动画
          showToast('🎉 捞到漂流瓶啦！', 'success');
          
          // 重置漂流瓶位置
          setTimeout(() => {
            this.bottleTransform = { y: 0, rotate: 0 };
          }, 500);
          
        } catch (error) {
          console.error('捞取漂流瓶失败', error);
          showToast('捞取失败，请重试');
          
          // 重置漂流瓶位置
          this.bottleTransform = { y: 0, rotate: 0 };
        } finally {
          this.isPicking = false;
        }
      },
      
      // 回复漂流瓶
      respondToBottle() {
        if (this.currentBottle) {
          showToast('回复功能开发中...');
          // 这里可以跳转到回复页面
          // uni.navigateTo({
          //   url: `/pages/bottle/respond-bottle?id=${this.currentBottle.id}`
          // });
        }
      },
      
      // 喜欢漂流瓶
      likeBottle() {
        showToast('❤️ 已添加到喜欢');
      },
      
      // 收藏漂流瓶
      collectBottle() {
        showToast('⭐ 已收藏');
      }
    }
  };
</script>

<style scoped>
  @import '../../src/style/global.scss';
  
  .pick-bottle-container {
    width: 100%;
    min-height: 100vh;
    padding: 40rpx 30rpx;
    color: var(--white);
    position: relative;
  }
  
  .header {
    text-align: center;
    margin-bottom: 50rpx;
  }
  
  .title {
    font-size: 48rpx;
    font-weight: bold;
    display: block;
    margin-bottom: 10rpx;
  }
  
  .subtitle {
    font-size: 28rpx;
    opacity: 0.8;
    display: block;
  }
  
  .main-content {
    display: flex;
    flex-direction: column;
    align-items: center;
  }
  
  .ocean {
    width: 100%;
    height: 400rpx;
    background: linear-gradient(to bottom, rgba(69, 183, 209, 0.2), rgba(69, 183, 209, 0.1));
    border-radius: 20rpx;
    margin-bottom: 40rpx;
    overflow: hidden;
    position: relative;
    display: flex;
    align-items: center;
    justify-content: center;
  }
  
  .bottle-animation {
    position: relative;
    width: 200rpx;
    height: 280rpx;
  }
  
  .bottle {
    position: relative;
    transition: all 0.5s ease;
  }
  
  .floating {
    animation: float 3s ease-in-out infinite;
  }
  
  .caught {
    animation: catch 1s ease-in-out;
  }
  
  .bottle-neck {
    width: 60rpx;
    height: 40rpx;
    background-color: rgba(255, 255, 255, 0.8);
    position: absolute;
    top: -40rpx;
    left: 50%;
    transform: translateX(-50%);
  }
  
  .bottle-body {
    width: 200rpx;
    height: 240rpx;
    background-color: rgba(255, 255, 255, 0.8);
    border-radius: 0 0 100rpx 100rpx;
    position: relative;
    overflow: hidden;
    display: flex;
    align-items: center;
    justify-content: center;
    padding: 30rpx;
  }
  
  .bottle-text {
    font-size: 24rpx;
    color: var(--text-color);
    text-align: center;
    line-height: 1.4;
  }
  
  .bottle-cap {
    width: 80rpx;
    height: 20rpx;
    background-color: #8B4513;
    position: absolute;
    top: -60rpx;
    left: 50%;
    transform: translateX(-50%);
    border-radius: 10rpx;
  }
  
  .pick-btn {
    width: 100%;
    max-width: 400rpx;
    height: 100rpx;
    font-size: 32rpx;
    font-weight: bold;
    margin-bottom: 40rpx;
  }
  
  .bottle-card {
    width: 100%;
    max-width: 600rpx;
    background-color: rgba(255, 255, 255, 0.1);
    border-radius: 20rpx;
    padding: 30rpx;
    margin-bottom: 30rpx;
    backdrop-filter: blur(10rpx);
    animation: slideUp 0.5s ease-out;
  }
  
  .bottle-info {
    display: flex;
    justify-content: space-between;
    margin-bottom: 20rpx;
    font-size: 24rpx;
    opacity: 0.8;
  }
  
  .bottle-content {
    font-size: 28rpx;
    line-height: 1.6;
    margin-bottom: 30rpx;
    min-height: 120rpx;
  }
  
  .bottle-actions {
    display: flex;
    justify-content: space-between;
  }
  
  .bottle-actions .btn {
    flex: 1;
    margin: 0 10rpx;
  }
  
  .stats {
    display: flex;
    justify-content: center;
    margin-bottom: 30rpx;
  }
  
  .stat-item {
    font-size: 24rpx;
    opacity: 0.8;
    margin: 0 20rpx;
  }
  
  .footer {
    text-align: center;
  }
  
  .tip-text {
    font-size: 24rpx;
    opacity: 0.7;
  }
  
  /* 动画定义 */
  @keyframes float {
    0%, 100% {
      transform: translateY(0) rotate(0deg);
    }
    50% {
      transform: translateY(-20rpx) rotate(5deg);
    }
  }
  
  @keyframes catch {
    0% {
      transform: translateY(0) rotate(0deg) scale(1);
    }
    50% {
      transform: translateY(-30rpx) rotate(10deg) scale(1.05);
    }
    100% {
      transform: translateY(0) rotate(0deg) scale(1);
    }
  }
  
  @keyframes slideUp {
    from {
      opacity: 0;
      transform: translateY(20rpx);
    }
    to {
      opacity: 1;
      transform: translateY(0);
    }
  }
</style>